# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import fields, models, api, tools, _
from odoo.exceptions import UserError, ValidationError
from odoo.tools.float_utils import float_compare


class PurchaseOrderLine(models.Model):
    _inherit = 'purchase.order.line'

    def _prepare_invoice_line(self):
        """
        Prepare the dict of values to create the new invoice line for a sales order line.

        :param qty: float quantity to invoice
        """
        self.ensure_one()
        if self.product_id.purchase_method == 'purchase':
            qty = self.product_qty - self.qty_invoiced
        else:
            qty = self.qty_received - self.qty_invoiced

        if float_compare(qty, 0.0, precision_rounding=self.product_uom.rounding) <= 0:
            qty = 0.0

        return {
            'name': '%s: %s' % (self.order_id.name, self.name),
            'currency_id': self.order_id.currency_id.id,
            'purchase_line_id': self.id,
            # 'date_maturity': move.invoice_date_due, # TBD: how to set it
            'product_id': self.product_id.id,
            'product_uom_id': self.product_uom.id,
            'price_unit': self.price_unit,
            'quantity': qty,
            'partner_id': self.order_id.partner_id.id,
            'analytic_account_id': self.account_analytic_id.id,
            'analytic_tag_ids': [(6, 0, self.analytic_tag_ids.ids)],
            'tax_ids': [(6, 0, self.taxes_id.ids)],
            'display_type': self.display_type,
        }


class PurchaseOrder(models.Model):
    _inherit = "purchase.order"

    def _prepare_invoice(self):
        """
        """
        self.ensure_one()
        journal = self.env['account.move'].with_context(
            force_company=self.company_id.id, default_type='in_invoice')._get_default_journal()
        if not journal:
            raise UserError(_('Please define an accounting puchase journal for the company %s (%s).') % (
                self.company_id.name, self.company_id.id))

        invoice_vals = {
            'ref': self.partner_ref or '',
            'type': 'in_invoice',
            'purchase_id': self.id,

            'currency_id': self.currency_id.id,  # po._onchange
            'invoice_user_id': self.user_id and self.user_id.id,
            'partner_id': self.partner_id.id,
            # po._onchange_purchase_auto_complete
            'fiscal_position_id': self.fiscal_position_id.id,
            'invoice_origin': self.name,
            'invoice_payment_term_id': self.payment_term_id.id,  # po._onchange
            'invoice_line_ids': [],
        }
        return invoice_vals

    def _create_invoices(self):
        # 暂时没用了,
        # 早期, 不知道 onchange 如何用, 这里 模仿 sale order 做了 创建账单 的 方法.
        # 现在 可以正确使用 onchange 方法.
        # po 创建 账单, 直接使用 odoo 本身的方法,
        # 根据 po , 调用 账单的 default_get 和 onchange, 然后 create

        # 这里保留 暂存, 模仿 sale order, 从 po 创建账单的方法,
        # 1) Create invoices.
        invoice_vals_list = []
        for order in self:
            # Invoice values.
            invoice_vals = order._prepare_invoice()

            # Invoice line values (应该减去 已经开票的 TBD).
            for line in order.order_line.filtered(lambda l: not l.display_type):
                invoice_vals['invoice_line_ids'].append(
                    (0, 0, line._prepare_invoice_line()))

            invoice_vals_list.append(invoice_vals)

        in_invoice_vals_list = invoice_vals_list

        # Create invoices.
        moves = self.env['account.move'].with_context(
            default_type='in_invoice').create(in_invoice_vals_list)
        return moves
